package cn.hy.service;

import cn.hy.properties.IpProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class IpCountService {
    private Map<String, Integer> ipCountMap = new HashMap<>();
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private IpProperties ipProperties;

    public void count() {
        String ip = httpServletRequest.getRemoteAddr();
        ipCountMap.put(ip, ipCountMap.getOrDefault(ip, 0) + 1);
    }

    @Scheduled(cron = "0/#{ipProperties.cycle}  * * * * ?")
    public void print() {
        if (ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())) {
            System.out.println("         IP访问监控");
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.printf("|%18s  |%5d  |%n", key, value);
            }
            System.out.println("+--------------------+-------+");
        } else if (ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())) {
            System.out.println("     IP访问监控");
            System.out.println("+-----ip-address-----+");
            for (String key : ipCountMap.keySet()) {
                System.out.printf("|%18s  |%n", key);
            }
            System.out.println("+--------------------+");
        }
        //阶段内统计数据归零
        if (ipProperties.getCycleReset()) {
            ipCountMap.clear();
        }
    }
}
